package is.ru.honn.rupin.process;

import is.ru.honn.rupin.domain.Gender;
import is.ru.honn.rupin.feeds.FeedEntry;
import is.ru.honn.rupin.feeds.FeedException;
import is.ru.honn.rupin.feeds.FeedHandler;
import is.ru.honn.rupin.feeds.FeedReader;
import is.ru.honn.rupin.service.BoardNotFoundException;
import is.ru.honn.rupin.service.PinService;
import is.ru.honn.rupin.service.UserNotFoundException;
import is.ru.honn.rupin.service.UsernameExistsException;
import is.ruframework.process.RuAbstractProcess;
import is.ruframework.process.RuProcessContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.util.Locale;

/**
 * Created by Sigrún Inga Kristinsdóttir.
 * Date: 11.10.2012
 * Time: 11:52
 * copyright (c) sigruninga&susanne
 *
 * @author Sigrún Inga kristindóttir og Susanne Götz
 * @version 1.1
 */
public class PinImportProcess extends RuAbstractProcess implements FeedHandler
{
    /**
     * Breytur sem PinImportProcess þarf að nota
     * PinImportprocess notar föllin sem eru skilgreindir í PinServiceData
     */
    protected PinService pinService;
    FeedReader reader;
    RuProcessContext rpc = new RuProcessContext();  // gefur okku aðgang að params í process.xml
    MessageSource messageSource;
    // Breytur end

    /**
     * RssFeedReader read() kallar á þennan fall
     * Fallið býr til Pin sem er sett inn í gagnagrunn
     * Parameters "String username" og "String boardname" eru sótt í process.xml
     * @param entry
     */
    public void processEntry(FeedEntry entry)
    {
        try
        {
            pinService.createPin((String) rpc.getParams().get("username"),(String) rpc.getParams().get("name"),
                   entry.getLink(), entry.getDescription());
        }
        catch (BoardNotFoundException bex)
        {
            System.out.println("exception in process Entry" );
            System.out.println(bex.getMessage());
        }

    }

    /**
     * Fall sem undirbýr gögnin til vinnslu.
     */
    public void beforeProcess()
    {
        //System.out.println(Locale.getDefault());
        ApplicationContext context = new FileSystemXmlApplicationContext("app.xml");
        pinService = (PinService) context.getBean("pinService");
        // tenging við process.xml
        rpc.setParams(getProcessContext().getParams());
        try
        {
            // búum til default User með gögnin úr process.xml
            pinService.signUpUser((String) rpc.getParams().get("username"), (String)rpc.getParams().get("firstName"),
                    (String)rpc.getParams().get("lastName"),(String) rpc.getParams().get("email"),
                    (String)rpc.getParams().get("password"),  Gender.valueOf((String) rpc.getParams().get("gender")) );
            // búum til default Board með gögnin úr process.xml
            pinService.createBoard((String) rpc.getParams().get("username"), (String) rpc.getParams().get("name"),
                    (String) rpc.getParams().get("category"));
        }
        catch (UsernameExistsException uee)
        {
            System.out.println(uee.getMessage());
        }
        catch (UserNotFoundException e)
        {
            System.out.println(e.getMessage());
        }

        reader = (FeedReader) context.getBean("feedReader");
        reader.setFeedHandler(this);
        messageSource = (MessageSource) context.getBean("messageSource");
        log.info(messageSource.getMessage("processbefore", new Object[]{getProcessContext().getProcessName()},
                Locale.getDefault()));
    }

    /**
     *  Fall sem les gögnin, býr til pinnar og skráir þeim í gagnagrunn
     *  Hér er notað read() sem kallar á processEntry
     */
    @Override
    public void startProcess()
    {
        log.info(messageSource.getMessage("processstart", new Object[]{getProcessContext().getProcessName()},
                       Locale.getDefault()));
               try
               {
                   // frumstillum source sem er notað í read()
                   reader.setSource(getProcessContext().getImportURL());
                   reader.read();
               }
               catch(FeedException e)
               {
                   log.info(messageSource.getMessage("processreaderror",
                           new Object[]{getProcessContext().getImportFile()},
                           Locale.getDefault()));
                   log.info(e.getMessage());
               }

        log.info(messageSource.getMessage("processstartdone",
                new Object[]{pinService.getPinsOnBoard((String) rpc.getParams().get("username"),
                        (String) rpc.getParams().get("name")).size()},
                Locale.getDefault())) ;
    }

    /**
     * Sækir öll pins sem eru skráð á default borð og default notanda og
     * loggar þau
     * Loggar þegar process er búinn
     */
    public void afterProcess()
       {
           /*
           List<Pin> pin = pinService.getPinsOnBoard((String) rpc.getParams().get("username"),
                   (String) rpc.getParams().get("name"));
           for (Pin p : pin)
           {
               System.out.println(p.getDescription());
           }
           System.out.println("\n Finished printing all pins");
           */
           log.info(messageSource.getMessage("processfinished",
                          new Object[]{pinService.getPinsOnBoard((String) rpc.getParams().get("username"),
                                  (String) rpc.getParams().get("name"))},
                          Locale.getDefault())) ;
       }
}
